<template>
  <div class="user_select_tree">
    <!-- <el-tree
      ref="userTree"
      :data="treeList"
      :props="defaultProps"
      :show-checkbox="multipleTree"
      default-expand-all
      :render-content="renderContent"
      @check="checkClick"
    /> -->
    <div v-show="multipleTree">
      <el-tree
        ref="userTreeMutiple"
        :data="treeList"
        :props="defaultProps"
        :show-checkbox="true"
        :render-content="renderContent"
        :highlight-current="false"
        :default-expanded-keys="expandedKeys"
        node-key="id"
        @check="checkClick"
        @node-expand="expand"
        @node-collapse="collapse"
      />
    </div>
    <div v-show="!multipleTree">
      <el-tree
        ref="userTreeSingle"
        :data="treeList"
        :props="defaultProps"
        node-key="id"
        :render-content="renderContent"
        :highlight-current="false"
        :default-expanded-keys="expandedKeys"
        @node-click="handleNodeClick"
        @node-expand="expand"
        @node-collapse="collapse"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'Index',
  props: {
    multipleTree: {
      type: Boolean,
      default: () => false,
    },
    ids: {
      type: Array,
      default: () => [],
    },
    multipleChange: {
      type: Object,
      default: () => {},
    },
    singleChange: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'text',
      },
      expandedKeys: [],
    };
  },
  watch: {
    multipleChange(nv, ov) {
      this.$refs.userTreeSingle.store.nodesMap[nv.id].expanded = nv.expanded;
    },
    singleChange(nv, ov) {
      this.$refs.userTreeMutiple.store.nodesMap[nv.id].expanded = nv.expanded;
    },
  },
  created() {
    this.getUserTree();
  },
  methods: {
    renderContent(h, { node, data, store }) {
      if (!data.leaf) {
        if (node.expanded) {
          return (
            // 展开树节点
            <span>
              <span class="tree_icon_wrp"><i class="tree_icon jeicon jeicon-folders"></i></span>
              <span class="tree_label">{node.label}</span>
            </span>
          );
        }
        return (
          // 闭合树节点
          <span>
            <span class="tree_icon_wrp"><i class="tree_icon jeicon jeicon-folder"></i></span>
            <span class="tree_label">{node.label}</span>
          </span>
        );
      }
      return (
        <span>
          <span class="tree_icon_wrp"><i class="tree_icon jeicon jeicon-text-field"></i></span>
          <span class="tree_label">{node.label}</span>
        </span>
      );
    },
    getUserTree() {
      const ddList = [
        {
          ddCode: 'JE_CORE_DEPTUSER_NODISABLE',
          async: false,
          rootId: '',
          ddName: '',
          whereSql: '',
          orderSql: '',
          parentSql: '',
          nodeInfo: '',
          params: {},
          initParams: {},
          moreRoot: false,
          queryField: '',
          nodeField: '',
          formatValue: '',
        },
      ];
      const params = {
        node: 'ROOT',
        onlyItem: true,
        excludes: 'checked',
        strData: JSON.stringify(ddList),
      };
      const list = JE.ajax({
        url: '/je/dd/tree/loadTree',
        params,
      });
      const addKey = (data) => {
        const item = [];
        data.map((list) => {
          const newData = { ...list };
          newData.disabled = false;
          newData.children = list.children.length ? addKey(list.children) : []; // 如果还有子集，就再次调用自己
          if (list.parent === 'ROOT') {
            this.expandedKeys.push(list.id);
          }
          item.push(newData);
        });
        return item;
      };
      this.treeList = addKey(list);
    },
    handleNodeClick(data, node, store) {
      // 单选，leaf为真是是子节点
      if (!this.multipleTree && data.leaf) {
        this.$nextTick(() => {
          const active = document.querySelectorAll('.is-current')[0];
          let classVal = document.querySelectorAll('.is-current')[0].getAttribute('class');
          // 再次点击同一人，去掉addSelectClass，清空ids
          if (this.ids[0] == data.id) {
            this.ids = [];
            classVal = classVal.replace(' addSelectClass', '');
          } else {
            classVal += ' addSelectClass';
            this.ids[0] = data.id;
          }
          active.setAttribute('class', classVal);
          this.$emit('list', this.ids);
        });
      }
    },
    checkClick(data, checkedData) {
      // 多选，返回选择的list数组
      if (data.leaf) {
        const index = this.ids.indexOf(data.id);
        if (index >= 0) {
          this.ids.splice(index, 1);
        } else {
          this.ids.push(data.id);
        }
      } else {
        const datalist = checkedData.checkedNodes.filter(x => x.leaf);
        this.ids = datalist.map(item => item.id);
      }
      this.$emit('list', this.ids);
    },
    /**
     * 展开（expand），收起（collapse）
     * 单选展开/收起向父组件emit当前节点的id和展开/收起状态和singleFunc；多选状态向父组件emit multipleFunc
     * 在父组件接受并保存节点id和状态
     * 如果点击的是单选树，则向multipleTree=true的selectTree发送singleChange，并在watch中执行singleChange
     * 如果点击的是多选树，则向multipleTree=false的selectTree发送multipleChange，并在watch中执行multipleChange
     */
    expand(data, node, store) {
      const obj = {
        id: data.id,
        expanded: true,
      };
      if (this.multipleTree) {
        this.$emit('multipleFunc', obj);
        return;
      }
      this.$emit('singleFunc', obj);
    },
    collapse(data, node, store) {
      const obj = {
        id: data.id,
        expanded: false,
      };
      if (this.multipleTree) {
        this.$emit('multipleFunc', obj);
        return;
      }
      this.$emit('singleFunc', obj);
    },
  },
};
</script>

<style lang="less">
.user_select_tree {
  .tree_icon_wrp {
    display: inline-block;
    width: 20px;
  }
  .tree_icon {
    font-size: 13px;

    &.jeicon-folders {
      color: #ECC01C;
    }
    &.jeicon-folder {
      color: #ECC01C;
      font-size: 12px;
    }
  }
  // .el-tree-node:hover>.el-tree-node__content,
  .el-tree-node:focus>.el-tree-node__content {
    background: #ffffff;
  }
  .addSelectClass {
    color: #536dfe;
  }
  .photo {
    width: 32px;
    height: 32px;
    border-radius: 100%;
  }
}
</style>
